#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2010 - BidiX@BidiX.info
#
#
'''
    webapp - specialize some Class and functions from google.appengine.ext.webapp
    
    Description :
 
     Usage : 
         Use Application in WSGIApplication remplacement
     
'''

from google.appengine.ext.webapp import WSGIApplication
from google.appengine.ext.webapp import Request
from google.appengine.ext.webapp import Response

class Application(WSGIApplication):
    '''
    functions :
        __call__()
            Patch from WSGIApplication.__call__ 
            Provides the match return from the regexp.match(request.path)
            {handlers}.match = regexp.match(request.path)
    '''

    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""
        request = Request(environ)
        response = Response()

        WSGIApplication.active_instance = self

        handler = None
        groups = ()
        for regexp, handler_class in self._url_mapping:
            match = regexp.match(request.path)
            if match:
                handler = handler_class()
                handler.match = match    # BidiX 2008-05-22
                handler.initialize(request, response)
                groups = match.groups()
                break
        self.current_request_args = groups

        if handler:
            try:
                method = environ['REQUEST_METHOD']
                if method == 'GET':
                    handler.get(*groups)
                elif method == 'POST':
                    handler.post(*groups)
                elif method == 'HEAD':
                    handler.head(*groups)
                elif method == 'OPTIONS':
                    handler.options(*groups)
                elif method == 'PUT':
                    handler.put(*groups)
                elif method == 'DELETE':
                    handler.delete(*groups)
                elif method == 'TRACE':
                    handler.trace(*groups)
                else:
                    handler.error(501)
            except Exception, e:
                #handler.handle_exception(e, self.__debug) # BidiX 2008-05-22
                handler.handle_exception(e, True) # BidiX 2008-05-22
        else:
            response.set_status(404)

        response.wsgi_write(start_response)
        return ['']

        